﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataAccess_Layer;
using Business_Layer;
using System.Collections;
public partial class MyAdmin_LichSuMuaHang_AM : System.Web.UI.Page
{
    long? tkGiaTu = null;
    long? tkGiaDen = null;
    DateTime? tkTuNgay = null;
    DateTime? tkDenNgay = null;
    LogAction log = new LogAction();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Helper.getCurrentAdminQuyen(this.Master) == QuyenTruyCap.QuyenXem)
        {
            // xử lý quyền xem
            ((CommandField)gvDSLichSuMuaHang_AM.Columns[0]).ShowDeleteButton = false;
            CommandField dtCmdField = ((CommandField)dtvLichSuMuaHang.Fields[dtvLichSuMuaHang.Fields.Count - 1]);
            dtCmdField.ShowEditButton = false;
            dtCmdField.ShowInsertButton = false;
            XoaNhieuBUTTON.Visible = false;
        }
        else if (Helper.getCurrentAdminQuyen(this.Master) == QuyenTruyCap.QuyenChinhSua)
        {
            // xử lý quyền chỉnh sửa
        }

        //Tim kiem theo parameter truyen vao theo cu phap: [TuNgay=...] [DenNgay=...][&GiaTu=...][&GiaDen=...]


        if (Request.Params["TuNgay"] != null) tkTuNgay = DateTime.Parse(Request.Params["TuNgay"]);
        if (Request.Params["DenNgay"] != null) tkDenNgay = DateTime.Parse(Request.Params["DenNgay"]);
        if (Request.Params["GiaTu"] != null)
        {
            tkGiaTu = long.Parse(Request.Params["GiaTu"]);
            tkGiaTu = tkGiaTu == -1 ? null : tkGiaTu;

            tkGiaDen = long.Parse(Request.Params["GiaDen"]);
            tkGiaDen = tkGiaDen == -1 ? null : tkGiaDen;
        }

        if (!IsPostBack)
        {
            initTextBox();
        }

        List<int> checkedCheckBoxRowIndex = getCheckedCheckBoxRowIndexes(gvDSLichSuMuaHang_AM);
        initDataSource();
        restoreCheckedCheckBox(checkedCheckBoxRowIndex);

        if ((tkGiaTu != null || tkGiaDen != null || tkTuNgay != null || tkDenNgay != null) && gvDSLichSuMuaHang_AM.Rows.Count == 0)
        {
            lblTBKhongTimThay.Visible = true;
            dtvLichSuMuaHang.Visible = false;
        }

        lblThongBaoDTView.Visible = false;
        lblThongBaoGridView.Visible = false;
    }

    private void restoreCheckedCheckBox(List<int> checkedCheckBoxRowIndex)
    {
        if (checkedCheckBoxRowIndex == null)
        {
            return;
        }

        int lastCellIndex = gvDSLichSuMuaHang_AM.Rows[0].Cells.Count - 1;
        foreach (int rowIndex in checkedCheckBoxRowIndex)
        {
            ((CheckBox)gvDSLichSuMuaHang_AM.Rows[rowIndex].Cells[lastCellIndex].FindControl("checkXoa")).Checked = true;
        }
    }

    private List<int> getCheckedCheckBoxRowIndexes(GridView gvDSLichSuMuaHang_AM)
    {
        if (gvDSLichSuMuaHang_AM.Rows.Count == 0)
        {
            return null;
        }

        List<int> rowIndexes = new List<int>();
        int lastCellIndex = gvDSLichSuMuaHang_AM.Rows[0].Cells.Count - 1;
        foreach (GridViewRow r in gvDSLichSuMuaHang_AM.Rows)
        {
            CheckBox checkXoa = (CheckBox)r.Cells[lastCellIndex].FindControl("checkXoa");
            if (checkXoa.Checked)
            {
                rowIndexes.Add(r.RowIndex);
            }
        }

        return rowIndexes;
    }

    private void initTextBox()
    {
        txtGiaTu.Text = (tkGiaTu == null) ? txtGiaTu.Text : tkGiaTu.ToString();
        txtGiaDen.Text = (tkGiaDen == null) ? txtGiaDen.Text : tkGiaDen.ToString();
        calTuNgayLap.SelectedDate = (tkTuNgay == null) ? DateTime.Now.Date : tkTuNgay.Value;
        calDenNgayLap.SelectedDate = (tkDenNgay == null) ? DateTime.Now.Date : tkDenNgay.Value;
    }

    protected void cbbKhachHang_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList cbbKhachHang = (DropDownList)dtvLichSuMuaHang.FindControl("cbbKhachHang");
        TextBox txtTenKhachHang = (TextBox)dtvLichSuMuaHang.FindControl("txtTenKhachHang");
        txtTenKhachHang.Text = cbbKhachHang.SelectedValue;
    }

    protected void cbbKhachHang_DataBound(object sender, EventArgs e)
    {
        DropDownList cbbKH = (DropDownList)dtvLichSuMuaHang.FindControl("cbbKhachHang");
        TextBox txtTenKhachHang = (TextBox)dtvLichSuMuaHang.FindControl("txtTenKhachHang");

        if (dtvLichSuMuaHang.CurrentMode == DetailsViewMode.Edit)
        {
            cbbKH.SelectedValue = txtTenKhachHang.Text;
        }
        else if (dtvLichSuMuaHang.CurrentMode == DetailsViewMode.Insert)
        {
            txtTenKhachHang.Text = cbbKH.SelectedValue;
        }
    }

    protected void XoaNhieuBUTTON_Click(object sender, EventArgs e)
    {
        string ids = "";
        List<long> deletedIDs = new List<long>();
        int lastCellIndex = gvDSLichSuMuaHang_AM.Rows[0].Cells.Count - 1;
        foreach (GridViewRow r in gvDSLichSuMuaHang_AM.Rows)
        {
            CheckBox checkXoa = (CheckBox)r.Cells[lastCellIndex].FindControl("checkXoa");
            if (checkXoa.Checked)
            {
                long id = long.Parse(r.Cells[1].Text);
                deletedIDs.Add(id);
                ids += id.ToString() + ", ";
            }
        }

        lblThongBaoGridView.Visible = true;
        lblThongBaoGridView.Text = "Xóa thành công record: " + ids.Substring(0, ids.LastIndexOf(", "));
        //log
        log.TenLoaiCapNhat = "Xóa";
        log.Ngay = DateTime.Now;
        log.TenBang = "Bảng Lịch sử mua hàng";
        log.TenLoaiDangNhap = "Admin";
        log.TenDangNhap = Helper.getCurrentAdminUserName(Session);
        string logText = "";
        log.DuLieuCu = "record ID:" + ids.Substring(0, ids.LastIndexOf(", "));
        logText = "x";
        log.DuLieuMoi = logText;
        Log_BUS.insert(log);
        //log
        try
        {
            DataAccess_Layer.LichSuMuaHang_DAC.delete(deletedIDs);
        }
        catch (System.Exception ex)
        {
            lblThongBaoGridView.Text = "Xóa thất bại!";
        }

        initDataSource();
        refreshDetailViewPageIndex();
    }

    private void initDataSource()
    {
        refreshGV();
        gvDSLichSuMuaHang_AM.SelectedIndex = gvDSLichSuMuaHang_AM.SelectedIndex == -1 ? 0 : gvDSLichSuMuaHang_AM.SelectedIndex;
        dtvLichSuMuaHang.PageIndex = Helper.calPageIndexForDetailView(gvDSLichSuMuaHang_AM);
    }

    private void refreshGV()
    {
        gvDSLichSuMuaHang_AM.DataSource = DataAccess_Layer.LichSuMuaHang_DAC.timKiem_LSMH(tkTuNgay, tkDenNgay, tkGiaTu, tkGiaDen);
        gvDSLichSuMuaHang_AM.DataBind();
    }

    private void refreshDetailViewPageIndex()
    {
        dtvLichSuMuaHang.DataBind();
        dtvLichSuMuaHang.PageIndex = Helper.calPageIndexForDetailView(gvDSLichSuMuaHang_AM);
    }

    protected void btnTimKiem_Click(object sender, EventArgs e)
    {
        long? giaTu = -1;
        long? giaDen = -1;

        if (txtGiaTu.Text.Length != 0)
            giaTu = long.Parse(txtGiaTu.Text);
        else
            giaTu = -1;

        if (txtGiaDen.Text.Length != 0)
            giaDen = long.Parse(txtGiaDen.Text);
        else
            giaDen = -1;


        DateTime? tuNgay = calTuNgayLap.SelectedDate;
        DateTime? denNgay = calDenNgayLap.SelectedDate;

        string url = "LichSuMuaHang_AM.aspx?GiaTu=" + giaTu + "&GiaDen=" + giaDen;

        if (tuNgay != null) url += "&TuNgay=" + tuNgay.Value.ToShortDateString();
        if (denNgay != null) url += "&DenNgay=" + denNgay.Value.ToShortDateString();

        Response.Redirect(url);
    }
    protected void gvDSLichSuMuaHang_AM_SelectedIndexChanged(object sender, EventArgs e)
    {
        refreshDetailViewPageIndex();
    }
    protected void gvDSLichSuMuaHang_AM_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        Helper.changeGVPageIndex(gvDSLichSuMuaHang_AM, e.NewPageIndex);
        gvDSLichSuMuaHang_AM.SelectedIndex = gvDSLichSuMuaHang_AM.Rows.Count > 0 ? 0 : -1;
        dtvLichSuMuaHang.PageIndex = Helper.calPageIndexForDetailView(gvDSLichSuMuaHang_AM);
    }
    protected void dtvLichSuMuaHang_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
    {
        refreshGV();
        Helper.changeGVPageIndex(gvDSLichSuMuaHang_AM, gvDSLichSuMuaHang_AM.PageCount - 1);
        gvDSLichSuMuaHang_AM.SelectedIndex = gvDSLichSuMuaHang_AM.Rows.Count - 1;
        refreshDetailViewPageIndex();
    }
    protected void dtvLichSuMuaHang_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
    {
        refreshGV();
        refreshDetailViewPageIndex();
    }
    protected void LQDSLichSuMuaHang_Updating(object sender, LinqDataSourceUpdateEventArgs e)
    {        
        DataAccess_Layer.LichSuMuaHang newHistory = new DataAccess_Layer.LichSuMuaHang();
        newHistory.ID = int.Parse(dtvLichSuMuaHang.Rows[0].Cells[1].Text);
        newHistory.ID_Customer = long.Parse(((DropDownList)dtvLichSuMuaHang.Rows[3].Cells[1].FindControl("cbbKhachHang")).SelectedValue);
        newHistory.NgayLapHoaDon = ((Calendar)dtvLichSuMuaHang.Rows[1].Cells[1].FindControl("CreatedDateEditCALENDAR")).SelectedDate.ToShortDateString();
        newHistory.TongTien = ((TextBox)dtvLichSuMuaHang.Rows[2].Cells[1].Controls[0]).Text;

        //log
        try
        {
            log.TenLoaiCapNhat = "cập nhật";
            log.Ngay = DateTime.Now;
            log.TenBang = "Bảng lịch sử mua hàng";
            log.TenLoaiDangNhap = "Adminstator";
            log.TenDangNhap = Helper.getCurrentAdminUserName(Session);

            DataAccess_Layer.LichSuMuaHang logO = DataAccess_Layer.LichSuMuaHang_DAC.lay(newHistory.ID);

            log.DuLieuCu = "Ngày lập hóa đơn: " + logO.NgayLapHoaDon
                + "..\nTổng tiền: " + logO.TongTien
                + "..\nKhách hàng: " + logO.Customer;


            logO = newHistory;
            log.DuLieuMoi = "Ngày lập hóa đơn: " + logO.NgayLapHoaDon
                + "..\nTổng tiền: " + logO.TongTien
                + "..\nKhách hàng: " + logO.Customer;
            Log_BUS.insert(log);
        }
        catch { }

        //log
        lblThongBaoDTView.Visible = true;
        try
        {
            DataAccess_Layer.LichSuMuaHang_DAC.update(newHistory);
            lblThongBaoDTView.Text = "Cập nhật thành công record có ID là " + newHistory.ID;
        }
        catch (System.Exception ex)
        {
            lblThongBaoDTView.Text = "Cập nhật thất bại record có ID là " + newHistory.ID;
        }

        e.Cancel = true;
        e.ExceptionHandled = true;
    }
    protected void LQDSLichSuMuaHang_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        e.Result = gvDSLichSuMuaHang_AM.DataSource;
    }
    protected void LQDSLichSuMuaHang_Inserted(object sender, LinqDataSourceStatusEventArgs e)
    {//log
        try
        {
            log.TenLoaiCapNhat = "Thêm";
            log.Ngay = DateTime.Now;
            log.TenBang = "Bảng Lịch sử mua hàng";
            log.TenLoaiDangNhap = "Adminstator";
            log.TenDangNhap = Helper.getCurrentAdminUserName(Session);

            DataAccess_Layer.LichSuMuaHang logO;

            log.DuLieuCu = "X";

            logO = (DataAccess_Layer.LichSuMuaHang)e.Result;
            log.DuLieuMoi = "Ngày lập hóa đơn: " + logO.NgayLapHoaDon
                + "..\nTổng tiền: " + logO.TongTien
                + "..\nKhách hàng: " + logO.Customer;
            Log_BUS.insert(log);
        }
        catch { }
        //log
        lblThongBaoDTView.Visible = true;
        DataAccess_Layer.LichSuMuaHang newOrder = (DataAccess_Layer.LichSuMuaHang)e.Result;

        if (e.Exception == null)
        {
            lblThongBaoDTView.Text = "Thêm thành công record có ID là " + newOrder.ID;
            return;
        }

        lblThongBaoDTView.Text = "Thêm thất bại record!";
        e.ExceptionHandled = true;
    }

    protected void CreatedDateEditCALENDAR_SelectionChanged(object sender, EventArgs e)
    {
        Calendar cal = (Calendar)sender;
        Label lbl = (Label)dtvLichSuMuaHang.FindControl("CreatedDateForEditLABEL");

        lbl.Text = cal.SelectedDate.ToShortDateString();
    }
    protected void dtvLichSuMuaHang_DataBound(object sender, EventArgs e)
    {
        Calendar cal = null;
        Label lbl = null;

        if (dtvLichSuMuaHang.CurrentMode == DetailsViewMode.Edit)
        {
            cal = (Calendar)dtvLichSuMuaHang.FindControl("CreatedDateEditCALENDAR");
            lbl = (Label)dtvLichSuMuaHang.FindControl("CreatedDateForEditLABEL");
            DateTime dt = DateTime.Parse(lbl.Text);
            cal.SelectedDate = dt;
            cal.VisibleDate = dt;
        }
        else if (dtvLichSuMuaHang.CurrentMode == DetailsViewMode.Insert)
        {
            cal = (Calendar)dtvLichSuMuaHang.FindControl("CreatedDateInsertCALENDAR");
            lbl = (Label)dtvLichSuMuaHang.FindControl("CreatedDateForInsertLABEL");
            cal.SelectedDate = DateTime.Now;
            cal.VisibleDate = DateTime.Now;

            lbl.Text = DateTime.Now.ToShortDateString();
        }
    }
    protected void CreatedDateInsertCALENDAR_SelectionChanged(object sender, EventArgs e)
    {
        Calendar cal = (Calendar)sender;
        Label lbl = (Label)dtvLichSuMuaHang.FindControl("CreatedDateForInsertLABEL");

        lbl.Text = cal.SelectedDate.ToShortDateString();
    }
}